package org.kugua.utils;

import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Optional;
import java.util.Random;
import java.util.Set;

/**
 * RandomUtils
 *
 * @author 苦瓜
 * @create 2024-08-27
 * @since 1.0.0
 */
public class RandomUtils {

    private static final Random random = new SecureRandom();

    public static Integer random(Integer maxValue) {
        return random.nextInt(maxValue);
    }

    /**
     * 算法效率相对低下， 待优化
     *
     * @param maxValue 随机数最大值
     * @param alreayGenSet 已经生成的随机数
     * @param accuracy 精度
     * @return 随机数
     */
    public static Integer random(Integer maxValue, Set<Integer> alreayGenSet, Integer accuracy) {
        while (true) {
            int randValue = random.nextInt(maxValue);
            boolean b = Optional.ofNullable(alreayGenSet).orElseGet(HashSet::new)
                    .parallelStream()
                    .anyMatch(r -> Math.abs(r - randValue) <= accuracy);
            if (!b) {
                return randValue;
            }
        }
    }

    public static Integer random(Integer minValue, Integer maxValue) {
        return random.nextInt(maxValue - minValue) + minValue;
    };

    public static Double random(Double maxValue) {
        return random.nextDouble(maxValue);
    }

    public static Double random(Double minValue, Double maxValue) {
        return random.nextDouble(maxValue - minValue) + minValue;
    }
}
